import {reactive, ref} from 'vue'
import { queryOneAddressApi, submitOrderApi }  from '@/api'
import { queryDefaultAddressAPI } from '/api/address'
import {getOrderDetailAPI, updateOrderAPI} from '@/api/order'
import BASE_URL from "@/utils/env";
export function useCreateOrderData() {
    let fromAddressData = ref(null)
    let toAddressData = ref(null)
    const fileList = ref([])
    const orderFormData = reactive({
        goodsName: '',
        weight: 0,
        typeId: 1,
        typeName: '代拿快递',
        tips: 0,
        description: '',
        picture:'',
        takeAddressId: '',
        receiveAddressId: '',
        remark: '',
        id: null
    })
    const loading = ref(false)
    function handleSubmitOrder() {
        loading.value = true
        if(orderFormData.id) {
            updateOrderAPI(orderFormData).then(result =>{
                uni.showToast({title: '修改订单成功', icon: 'none', duration: 2000})
                loading.value = false
                uni.navigateTo({url: '/pages/order/order?type=create'})
            })
        } else {
            submitOrderApi(orderFormData).then(res => {
                uni.showToast({title: '下单成功', icon: 'none', duration: 2000})
                uni.navigateTo({url: '/pages/order/order?type=create'})
            }).finally(_ =>{
                loading.value = false
            })
        }
    }
    function getOneAddress(id,type) {
        queryOneAddressApi(id).then(res => {
            if(type === "to") {
                toAddressData.value = res
            } else {
                fromAddressData.value = res
            }
        })
    }

    function getDefaultAddress() {
        queryDefaultAddressAPI().then(res =>{
            if(res) {
                toAddressData.value = res
                orderFormData.receiveAddressId = res.id
            }
        })
    }

    function getOrderDetail(orderId) {
        getOrderDetailAPI(orderId).then(res => {
            for (const key in orderFormData) {
                orderFormData[key] = res[key]
            }
            fileList.value = [{url: `${BASE_URL}images/${res['picture']}`}]
        })
    }
    return {
        getOneAddress,
        fromAddressData,
        toAddressData,
        orderFormData,
        handleSubmitOrder,
        loading,
        getDefaultAddress,
        getOrderDetail,
        fileList
    }
}
